import Koa from "koa"
import Router from "koa-router"
import bodyParser from "koa-bodyparser"
import { DataTypes, Sequelize,Op } from "sequelize"
import cors from "@koa/cors"

const app = new Koa()

const router = new Router()

app.use(cors())
app.use(bodyParser())

const sequelize = new Sequelize('bookDb','root','123456',{
    dialect:"mysql"

})

const Book = sequelize.define('book',{
    bookName:DataTypes.STRING,
    bookAuthor:DataTypes.STRING,
    bookPrice:DataTypes.STRING,
    bookNum:DataTypes.INTEGER
})

await sequelize.sync({force:true})

await  Book.bulkCreate(
    [
        {bookName:'白夜行',bookAuthor:'东野圭吾',bookPrice:'50￥',bookNum:100},
        {bookName:'狼王梦',bookAuthor:'沈石溪',bookPrice:'30￥',bookNum:100},
        {bookName:'红楼梦',bookAuthor:'曹雪芹',bookPrice:'40￥',bookNum:100},
        {bookName:'西游记',bookAuthor:'吴承恩',bookPrice:'60￥',bookNum:100}
    ]
)

//定义获取所有图书路由
router.get("/books",async(ctx)=>{
    let books;
    let keyword = ctx.request.query.keyword || ''

    if (keyword) {
        books = await Book.findAll({
            where:{
                [Op.or]:{
                    bookName:{
                        [Op.like]:`%${keyword}%`
                    },
                    bookAuthor:{
                        [Op.like]:`%${keyword}%`
                    },
                    bookPrice:{
                        [Op.like]:`%${keyword}%`
                    },
                    bookNum:{
                        [Op.like]:`%${keyword}%`
                    }
                }
            }
        })
    } else {
        books = await Book.findAll()
    }
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:books
    }
})

//定义获取单个图书路由
router.get("/book/:id",async(ctx)=>{
    let id = ctx.params.id
    let book = await Book.findByPk(id)
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:book
    }
})

//定义删除图书路由
router.delete("/book/:id",async(ctx)=>{
    let id = ctx.params.id
    let book = await Book.destroy({where:{id}})
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:book
    }
})

//定义更新图书路由
router.put("/book/:id",async(ctx)=>{
    let id = ctx.params.id
    let obj = ctx.request.body
    let book = await Book.update(obj,{where:{id}})
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:book
    }
})

//定义添加图书路由
router.post("/book",async(ctx)=>{
    let obj = ctx.request.body
    let book = await Book.create(obj)
    ctx.body = {
        code:1000,
        msg:'请求成功',
        data:book
    }
})

app.use(router.routes())
let port = 8000
app.listen(port)
console.log(`服务器运行于：http://localhost:${port}`);
